﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IMS_Data;

namespace IMS_WEB
{
    public partial class newOrder : System.Web.UI.Page
    {
        private string btnDelPrefix = "btnDel_";
        private string tbPrefix = "tb_";
        string contract_sn = "";
        order m_od = null;

        private string GenSN(order or)
        {
            if (or == null)
            {
                return "SH00001";
            }
            else
            {
                string val = or.contract_sn.Substring(2);
                int num = Convert.ToInt32(val);
                return "SH" + (num + 1).ToString("00000");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            contract_sn = Request.QueryString["ID"];
            if (!IsPostBack)
            {
                OrderReposity ort = new OrderReposity();
                order lastSN = ort.GetLastInsertOrder();

                tbOrderID.Text = GenSN(lastSN);

                if (!string.IsNullOrEmpty(contract_sn))
                {
                    OrderReposity or = new OrderReposity();

                    m_od = or.GetOrderByID(contract_sn);

                    CompanyReposity cr = new CompanyReposity();
                    company cp = cr.GetCompany(m_od.contract_supplier);

                    tbOrderID.Text = contract_sn;
                    tbCompany.Text = m_od.contract_supplier;
                    tbCompany.ReadOnly = true;
                    tbAddr.Text = cp.company_address;
                    tbAccount.Text = m_od.contract_account;
                    tbPhone.Text = m_od.contract_contactPhone;
                    tbTaxNumber.Text = m_od.contract_taxsn;

                    tbDate.Text = m_od.contract_date.HasValue ? m_od.contract_date.Value.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM-dd");

                    var ids = m_od.orderDetail.Select(dt => dt.product_id).Distinct();
                    foreach (var ele in ids)
                    {
                        int count = m_od.orderDetail.Count(cd=>cd.product_id == ele);
                        var tt = (from n in m_od.orderDetail where n.product_id == ele select n).FirstOrDefault();
                        AddProduct(tt.product, count);
                    }
                    
                }
            }
        }

        private List<int> GetRowList()
        {
            List<int> rowList = null;
            if (Session["rowNum"] == null)
            {
                rowList = new List<int>();
            }
            else
            {
                rowList = this.Session["rowNum"] as List<int>;
                if (rowList.Count != 0)
                {
                    rowList.Add(rowList[rowList.Count - 1] + 1);
                }
                else
                {
                    rowList.Add(0);
                }
               
            }
            return rowList;
        }

        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);

            if (!IsPostBack)
            {
                Session["rowNum"] = null;
            }
            if (Session["rowNum"] == null)
            {
                this.Session.Add("rowNum", GetRowList());
            }
            
            initTable();
            
        }

        private TableRow CreateRowControl(int rowIndex)
        {
            TableRow row = new TableRow();
            Unit[] sizes = new Unit[] { Unit.Pixel(150), Unit.Pixel(150), Unit.Pixel(80), Unit.Pixel(80), 
                Unit.Pixel(80), Unit.Pixel(80), Unit.Pixel(80), Unit.Pixel(80)};
            //string[] values = new string[] { pd.product_code, pd.product_name, pd.product_type, "", "", pd.product_price.Value.ToString(),"","" };
            
            for (int j = 1; j <= 8; j++)
            {
                TableCell cell = new TableCell();
                TextBox box = new TextBox();
                box.Width = sizes[j - 1];
                box.ID = tbPrefix + rowIndex.ToString() + j.ToString();
                cell.Controls.Add(box);
                row.Cells.Add(cell);
                
            }
            Button btn = new Button();
            btn.Text = "删除";
            btn.ID = btnDelPrefix + rowIndex.ToString();
            btn.Click += new EventHandler(btnDel_Click);
            TableCell cellDel = new TableCell();
            cellDel.Controls.Add(btn);
            row.Cells.Add(cellDel);
            return row;
        }

        void btnDel_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;

            string name = btn.Text;

            int rowIndex = Convert.ToInt32(btn.ID.Substring(btnDelPrefix.Length));

            List<int> rowList = this.Session["rowNum"] as List<int>;

            Table1.Rows.RemoveAt(rowList.IndexOf(rowIndex) + 1); // exclude head
            rowList.Remove(rowIndex);
        }

        private void initTable()
        {

            List<int> rowList = this.Session["rowNum"] as List<int>;
            if (rowList == null)
            {
                return;
            }
            foreach(int i in rowList)
            {
                this.Table1.Rows.Add(CreateRowControl(i));
            }
        }
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (dpdTextBox._DropDownList.SelectedIndex == -1)
            //{
            //    return;
            //}
            //int index = Convert.ToInt32(dpdTextBox._DropDownList.SelectedItem.Value);
            //CompanyReposity cr = new CompanyReposity();

            //dpdTextBox.Text = dpdTextBox._DropDownList.SelectedItem.Text;
            //var ele = cr.GetCompany(index);

            //if (ele != null)
            //{
            //    tbAccount.Text = ele.company_bankAccount;
            //    tbAddr.Text = ele.company_address;
            //    tbDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //    tbPhone.Text = ele.company_contactPhone;
            //    tbOrderID.Text = DateTime.Now.ToString("XAyyyyMMddHHmm");
            //    tbTaxNumber.Text = ele.company_tax;
            //}
        }

        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            ProductReposity pr = new ProductReposity();

            product pd = pr.GetProductByName(tbProductName.Text);

            AddProduct(pd,0);
        }

        private void AddProduct(product pd,int count)
        {
            if (pd == null)
            {
                return;
            }
            List<int> rowList = GetRowList();
            int rowNum = 0;
            if (rowList.Count > 0)
            {
                rowNum = rowList[rowList.Count - 1];
            }

            this.Table1.Rows.Add(CreateRowControl(rowNum));

            FillRowData(pd, rowNum, count);
        }
        private void FillRowData(product pd,int rowNum,int count)
        {
            TextBox tbCode = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "1");
            tbCode.Text = pd.product_code.Trim();

            TextBox tbName = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "2");
            tbName.Text = pd.product_name.Trim();

            TextBox tbType = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "3");
            tbType.Text = pd.product_type.Trim();

            TextBox tbUnit = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "4");
            tbUnit.Text = pd.product_unit.Trim();

            TextBox tbCount = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "5");
            tbCount.Text = count.ToString();

            TextBox tbPrice = (TextBox)Table1.FindControl(tbPrefix + rowNum.ToString() + "6");
            tbPrice.Text = pd.product_price.HasValue ? pd.product_price.Value.ToString():"0";


        }

        protected void btnQueryCompany_Click(object sender, EventArgs e)
        {
            CompanyReposity cr = new CompanyReposity();

            company cp = cr.GetCompany(tbCompany.Text);

            if (cp == null)
            {
                Response.Write("<script>alert('不存在该进货单位')</script>");
            }
            else
            {
                tbAccount.Text = cp.company_bankAccount;
                tbAddr.Text = cp.company_address;
                tbDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                tbPhone.Text = cp.company_phone;
                tbTaxNumber.Text = cp.company_tax;
            }
        }

        private IList<orderDetail> GetOrderDetails(List<product> proList)
        {
            List<orderDetail> ods = new List<orderDetail>();
            proList.Clear();
            List<int>  rowList = this.Session["rowNum"] as List<int>;
            ProductReposity pr = new ProductReposity();
            foreach (int ele in rowList)
            {
                
                TextBox tbName = (TextBox)Table1.FindControl(tbPrefix + ele.ToString() + "2");
                TextBox tbPrice = (TextBox)Table1.FindControl(tbPrefix + ele.ToString() + "6");
                TextBox tbCount = (TextBox)Table1.FindControl(tbPrefix + ele.ToString() + "5");


                product pd = pr.GetProductByName(tbName.Text);
                pd.product_price = Convert.ToDecimal(tbPrice.Text);
                proList.Add(pd);
                int nCount = Convert.ToInt32(tbCount.Text);
                for (int i = 0; i < nCount; i++)
                {
                    orderDetail od = new orderDetail();
                    od.product_id = pd.index_id;
                    od.index_id = new Random().Next() * -1;
                    od.product_status = CommonData.OrderInDraft;
                    ods.Add(od);
                }
            }

            return ods;
        }

        private void SaveOrUpdateOrder(string type,string opName)
        {
            
            OrderReposity or = new OrderReposity();
            order od = or.GetOrderByID(tbOrderID.Text);
            List<product> proList = new List<product>();
            if (od == null)
            {
                od = new order();
                od.contract_sn = tbOrderID.Text;
                od.contract_supplier = tbCompany.Text;
               
                od.contract_account = tbAccount.Text;
                od.contract_taxsn = tbTaxNumber.Text;
                od.contract_contactName = tbPhone.Text;
                od.contract_contactPhone = tbPhone.Text;

                od.contract_date = Convert.ToDateTime(tbDate.Text);
                od.contract_price = 10;
                od.contract_status = type;
                od.contract_remark = tbRemark.Text;
                od.contract_recver = tbRecver.Text;
                IList<orderDetail> ods = GetOrderDetails(proList);
                od.orderDetail.Clear();
                foreach (orderDetail ele in ods)
                {
                    ele.product_status = type;
                    od.orderDetail.Add(ele);
                }
                try
                {
                    or.AddOrder(od, proList);
                    Response.Write("<script>alert('订单" + opName + "成功')</script>");
                }
                catch (System.Exception ex)
                {
                    Response.Write("<script>alert('订单" + opName + "失败')</script>");
                }

            }
            else
            {
                try
                {
                    order newOrder = new order();
                    newOrder.contract_account = od.contract_account;
                    newOrder.contract_contactName = od.contract_contactName;
                    newOrder.contract_contactPhone = od.contract_contactPhone;
                    newOrder.contract_date = od.contract_date;
                    newOrder.contract_price = od.contract_price;
                    newOrder.contract_sn = od.contract_sn;
                    newOrder.contract_status = od.contract_status;
                    newOrder.contract_supplier = od.contract_supplier;
                    newOrder.contract_taxsn = od.contract_taxsn;
                    newOrder.index_id = od.index_id;
                    newOrder.contract_status = type;
                    newOrder.contract_recver = od.contract_recver;
                    newOrder.contract_remark = od.contract_remark;
                    newOrder.orderDetail = new System.Data.Objects.DataClasses.EntityCollection<orderDetail>();

                    IList<orderDetail> ods = GetOrderDetails(proList);

                    foreach (orderDetail ele in ods)
                    {
                        ele.product_status = type;
                        ele.order_id = newOrder.index_id;
                        newOrder.orderDetail.Add(ele);
                    }
                    or.UpdateOrder(newOrder, proList);
                    Response.Write("<script>alert('订单" + opName + "成功')</script>");
                }
                catch (System.Exception ex)
                {
                    Response.Write("<script>alert('订单" + opName + "失败')</script>");
                }

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveOrUpdateOrder(IMS_Data.CommonData.OrderInDraft, ((Button)sender).Text);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SaveOrUpdateOrder(IMS_Data.CommonData.OrderInCheck, ((Button)sender).Text);
        }
    }
}